
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

key_t key;
typedef struct msgbuff {
	long tp;
	char mm[100];
};
msgbuff mybufs, mybufr;
int len, n, msgid;
char buf[100];
int maxlen;
int msgtps, msgtpr;

int main(int argc, char **argv)
{
	if(argc < 2) {
		cout << "need argument" <<endl;
		exit(-1);
	} else {
		mybufs.tp = argv[1][0];
		mybufr.tp = argv[1][1];
	}
	maxlen = 100;
	if((key = ftok("som.dat", 0)) < 0) {
		cout << "can't create key" << endl;
		exit(-1);
	}
	if((msgid = msgget(key, IPC_CREAT|0644)) < 0) {
		cout << "something is incorrect" << endl;
		exit(-1);
	}
	while(1) 
	{
		len = msgrcv(msgid, &mybufr, maxlen, mybufr.tp, IPC_NOWAIT);
		if(len > 1) {	
			write(1, mybufr.mm, len);

                	if(!strcmp(mybufr.mm, "exit\n")) {
                        	cout << "end session !!"<< endl;
                        	msgctl(msgid, 0, 0);
                       		exit(-1); 
                	}
			continue;
                }
               	fgets(buf, 100, stdin);
		len = strlen(buf);
		strcpy(mybufs.mm, buf);
		if(msgsnd(msgid, &mybufs, len, 0) < 0) {
			msgctl(msgid, IPC_RMID, NULL);
			exit(-1);
		}
		if(!strcmp(buf, "exit\n")) {
			cout << "end session !!!" << endl; 
			msgctl(msgid, 0, 0);
			break;
		}
	}
	return 0;
}
